<?php
/**
 * @author by bilee.
 * 时间: 16/6/17 上午6:08
 * 帮你跑腿APP管理后台
 */
namespace Admin\Controller;

use Common\Controller\AdminbaseController;

class BdrunController extends AdminbaseController
{
    protected $user_level_model;
    protected $recharge_model;
    protected $order_queue_model;
    function _initialize()
    {
        parent::_initialize();
        $this->user_level_model = D("Common/UserLevel");
        $this->recharge_model = D("Common/UserRechargeDiscount");
        $this->order_queue_model = D("Common/OrderQueue");
    }
    //用户管理
    public function user(){

        $formget = I('formget');

        $mobile = $formget["mobile"];
        $user_name=  $formget["user_name"];
        $user_level_id=  intval($formget["user_level_id"]);
        $account_status=  intval($formget["account_status"]);
        $is_shop=  intval($formget["is_shop"]);

        $formget=array('mobile'=>$mobile
                        ,'user_name'=>$user_name
                        ,'user_level_id'=>$user_level_id
                        ,'account_status'=>$account_status
                        ,'is_shop'=>$is_shop);


        $where = " 1 " ;

        if($mobile)
            $where = $where.' and mobile like "%'.$mobile.'%"';
        if($user_name)
            $where = $where.' and user_name like "%'.$user_name.'%"';
        if($user_level_id!=-1)
            $where = $where.' and user_level_id = '.$user_level_id;
        if($is_shop!=-1)
            $where = $where.' and is_shop = '.$is_shop;

        $where = $where.' and account_status = '.$account_status;

        $users_model=M("app_users");
        $count=$users_model->where($where)->count();

        import("Org.Util.Pagemumayi");
        $page = new \Pagemumayi($count,20);
        //分页跳转的时候保证查询条件
        foreach($formget as $key=>$val) {
            $page->parameter .= 'formget['."$key"."]=".urlencode($val)."&";
        }

        $lists = $users_model->where($where)
            ->order("account_status desc,user_id DESC")
            ->limit($page->firstRow . ',' . $page->listRows)
            ->select();
        $this->assign('lists', $lists);
        $this->assign("formget", $formget);
        $this->assign("page", $page->show('Admin'));
        $this->assign('total_count', $count);
        $level_db = M('user_level');
        $this->assign('level_data', $level_db->select());
        $this->assign('shop_data', M('user_shop')->order('sort,time desc')->select());
//        dump($lists);
//        die;
        $this->display();
    }

    //用户冻结
    function freezee(){
        $id=intval($_GET['user_id']);
        if ($id) {
            $app_users = M("app_users");
            $rst =$app_users->where(array("user_id"=>$id))->save(array('account_status'=>0,'token'=>''));

            if ($rst) {
                $this->success("用户冻结成功！", U("bdrun/user",array('formget'=>I('formget'))));
            } else {
                $this->error('用户冻结失败！');
            }
        } else {
            $this->error('数据传入失败！');
        }

    }

    //用户启用
    function cancelfreezee(){
        $id=intval($_GET['user_id']);
        if ($id) {
            $rst = M("app_users")->where(array("user_id"=>$id))->setField('account_status',1);
            if ($rst) {
                $this->success("用户启用成功！", U("bdrun/user",array('formget'=>I('formget'))));
            } else {
                $this->error('用户启用失败！');
            }
        } else {
            $this->error('数据传入失败！');
        }
    }

    //管理首页
    public function index()
    {
        $this->display();
    }

    //我的地址
    public function address(){
        $detail_address=  I("detail_address");
        $where = " detail_address like '%".$detail_address."%'";
        $formget=array('detail_address'=>$detail_address);

        $address_model=M("common_address");

        $count=$address_model->where($where)->count();

        import("Org.Util.Pagemumayi");
        $page = new \Pagemumayi($count,20);
        //分页跳转的时候保证查询条件
        foreach($formget as $key=>$val) {
            $page->parameter .= "$key=".urlencode($val)."&";
        }

        $lists = $address_model
            ->where($where)
            ->order("address_type desc,user_id DESC")
            ->limit($page->firstRow . ',' . $page->listRows)
            ->select();

        $this->assign('formget',$formget);
        $this->assign('lists', $lists);
        $this->assign("page", $page->show('Admin'));
        //页面类型1，2转换为1：用户收藏2：历史记录
        $address_type=$address_model->where("address_type like '%'")->select();
        $address=array();
        foreach ($address_type as $a){
            $address[$a['id']]=$a;
        }

        $this->display();

    }

    //消息中心
    public function massage()
    {
        $this->display();
    }

    //用户级别
    public function user_level()
    {
        $user_level = M('user_level');
        $returns = $user_level->select();
        $this->assign('returns',$returns);
        $this->display();
    }

    //添加用户级别
    public function add_level()
    {
        if(IS_POST){
            if($this->user_level_model->create()) {
                $ret = $this->user_level_model->add();
                if ($ret) {
                    $this->success("新增成功！", U("user_level"));
                } else {
                    $this->error("新增失败！", U("user_level"));
                }
            }else{
                $this->error($this->user_level_model->getError());
            }
        }else{
            $this->display();
        }
    }

    //修改用户
    function edit_level()
    {
        if (IS_POST) {
            if ($this->user_level_model->create()) {
                $ret = $this->user_level_model->save();
                if($ret){
                    $this->success("修改成功！",U("user_level"));
                }else{
                    $this->error($this->user_level_model->getError());
                }
            }else{
                $this->error($this->user_level_model->getError());
            }
        } else {
            $ret = $this->user_level_model->where(array('user_level_id' => I('user_level_id')))->find();
            $this->assign('user_level', $ret);
            $this->display();
        }
    }

    //用户级别删除
    function delete_level()
    {
        $ret = $this->user_level_model->delete(I('user_level_id'));
        if($ret){
            $this->success("删除成功！",U("user_level"));
        }else{
            $this->error("删除失败");
        }
    }

    //订单管理
    public function order(){
        $order = M('order');
        $this->assign('orderdata',$order->select());
        $this->display();
    }

    /**
     * 充值优惠列表=================================
     */
    function recharge_list()
    {
        $this->assign('datas', $this->recharge_model->select());
        $this->display();
    }

    /**
     * 充值优惠编辑
     */
    function recharge_edit()
    {
        if (IS_POST) {
            if ($this->recharge_model->create()) {
                $ret = $this->recharge_model->save($_POST);
                if ($ret) {
                    $this->success("成功", U("rechargeList"));
                } else {
                    $this->error("失败", $this->recharge_model->getError());
                }
            } else {
                $this->error($this->recharge_model->getError());
            }
        } else {
            $ret = $this->recharge_model->where(array('id' => I('id')))->find();
            $this->assign('data', $ret);

            $this->display();
        }
    }

    /**
     * 充值优惠添加
     */
    function recharge_add()
    {
        if (IS_POST) {
            $_POST['time']=date('Y-m-d H-i-s',time());
            if ($this->recharge_model->create()) {

                $ret = $this->recharge_model->add();
                if ($ret) {
                    $this->success("成功", U("recharge_list"));
                } else {
                    $this->error("失败", $this->recharge_model->getError());
                }
            } else {
                $this->error($this->recharge_model->getError());
            }
        } else {
            $task = M('user_recharge_discount');
            $this->assign('data', $task->find());
            $this->display();
        }
    }
    /**
     * 充值优惠删除
     */
    function recharge_del()
    {
        $version_db = M("user_recharge_discount");
        $ret = $version_db->where('id='.I('id'))->delete();
        if ($ret) {
            $this->success("删除成功！", U("recharge_list"));
        } else {
            $this->error("删除失败");
        }
    }

    /**
     * 代排队列表=================================
     */
    function queue_list()
    {
        $order_number=  I("order_number");//订单号
        $queue_type=  I("queue_type");//订单类型
        $status=  intval(I("status"));//订单状态

        $start_time=  I("start_time");//开始时间
        $end_time=  I("end_time");//结束时间


        $formget=array('order_number'=>$order_number
        ,'queue_type'=>$queue_type,
            'status'=>$status,
            'start_time'=>$start_time,
            'end_time'=>$end_time);

        $where = " 1=1 ";

        if( $order_number)
            $where = $where." and order_number like '%".$order_number."%'";
        if( $queue_type)
            $where = $where." and queue_type like '%".$queue_type."%'";
        if($status!=-1)
            $where = $where.' and status = '.$status;
        if(!empty($start_time))
            $where = $where." and queue_time >= '".$start_time."  00:00:00'";
        if(!empty($end_time))
            $where = $where." and queue_time <= '".$end_time." 23:59:59' ";

        $count = $this->order_queue_model->where($where)->count();

        import("Org.Util.Pagemumayi");
        $page = new \Pagemumayi($count,20);
        //分页跳转的时候保证查询条件
        foreach($formget as $key=>$val) {
            $page->parameter .= "$key=".urlencode($val)."&";
        }

        $lists = $this->order_queue_model
            ->where($where)
            ->limit($page->firstRow . ',' . $page->listRows)
            ->select();
        
        $this->assign("formget",$formget);
        $this->assign('datas', $lists);
        $this->assign("page", $page->show('Admin'));

        $this->display();
    }

    /**
     * 代排队编辑
     */
    function queue_edit()
    {
        if (IS_POST) {
            if ($this->order_queue_model->create()) {
                $ret = $this->order_queue_model->save($_POST);
                if ($ret) {
                    $this->success("成功", U("queue_list"));
                } else {
                    $this->error("失败", $this->order_queue_model->getError());
                }
            } else {
                $this->error($this->order_queue_model->getError());
            }
        } else {
            $ret = $this->order_queue_model->where(array('queue_id' => I('queue_id')))->find();
            $this->assign('data', $ret);

            $this->display();
        }
    }

    /**
     * 代排队 查看详细信息
     */
    function queue_show(){
        $id=  intval(I("get.queue_id"));//
        $queue_db=M("order_queue");//创建与数据库表对应的实例对象
        $data = $queue_db->where(array("queue_id" => $id))->find();

        if (!$data) {
            $this->error("该排队订单不存在！");
        }

        //配送员
        $dispatch_obj = M("dispatch");
        $dispatch_data=$dispatch_obj->field("dispatch_id,dispatch_name,mobile,job_number")->select();
        $dispatchs=array();
        foreach ($dispatch_data as $u){
            $dispatchs[$u['dispatch_id']]=$u;
        }

        //取消事由
        $cancle_obj = M("cancle_reason");
        $cancle_data=$cancle_obj->field("cancle_reason_id,cancle_reason")->select();
        $cancles=array();
        foreach ($cancle_data as $u){
            $cancles[$u['cancle_reason_id']]=$u;
        }

        //优惠券
        $coupon_obj = M("user_coupon");
        $coupon_data=$coupon_obj->field("coupon_id,coupon_type")->select();
        $coupons=array();
        foreach ($coupon_data as $u){
            $coupons[$u['coupon_id']]=$u;
        }

        $this->assign("coupons", $coupons);
        $this->assign("dispatchs", $dispatchs);
        $this->assign("cancles", $cancles);
        $this->assign("data", $data);//在 Action 类里面使用 assign 方法对模板变量赋值，无论何种变量类型都统一使用 assign 赋值
        $this->display();// 输出模版文件
    }

    function push_server_data(){
        $order = M('order_queue');
        $order_ret = $order->where(array(
            'queue_id'=>I('queue_id')
        ))->field('queue_id,latit as startlat,lotit as startlon,queue_address as startaddress,order_money as money,queue_type as type,remark as remarks')->find();
        $order_data = json_encode($order_ret,true);
        push_server_data($order_data);
    }
    
        //查看
    function see(){
         $id=  intval(I("get.user_id"));//
        $users_model=M("app_users a");//创建与数据库表对应的实例对象
        $data = $users_model->where(array("user_id" => $id))
                             ->field('user_id,user_level_id,city_id,region,latitude,'
                                     . 'longitude,shop_latit,shop_longit,shop_scope,jpush_id,'
                                     . 'token,is_shop,shop_name,shop_address',true)->find();

        if (!$data) {
            $this->error("数据传入错误！");
        }


        $ordel_model = M("order");
        $where = "status = 7 and user_id = $id";
        //$count = $coin_message->where($where)->join('db_dispatch d ON m.dispatch_id=d.dispatch_id')->count();
        $data['order_count'] = $ordel_model->where($where)->count();

        $this->assign("formget",I('formget'));

        $this->assign("data", $data);//在 Action 类里面使用 assign 方法对模板变量赋值，无论何种变量类型都统一使用 assign 赋值
        $this->display();// 输出模版文件
}
    /**
     *设置使用积分
     **/
    function  used_points_value(){
        if (IS_POST) {
            $user_id = I("user_id");
            $new_points_value = intval(I("new_points_value"));
            $remark = I("remark");

            $user_db = M('app_users');
            $user_points_db = M('user_points');
            $user_obj = $user_db->field('points_value')->where('user_id=' . $user_id)->find();

            if($new_points_value <= 0 )
                $this->error('请输入兑换积分');
            if(!$remark )
                $this->error('请输入备注');

            if ($user_obj) {
                if(intval($user_obj['points_value']) < $new_points_value )
                    $this->error('兑换积分需小于账户积分');

                $data = array(
                    'user_id' => $user_id,
                    'points_type' => 3,
                    'points_value' => round($new_points_value * -1, 2),
                    'remark' => $remark,
                    'points_time' => date('Y-m-d H:i:s', time())
                );

                $add_ret = $user_points_db->add($data);

                $user_ret = $user_db->where('user_id=' . $user_id)->setField('points_value', $user_obj['points_value'] - $new_points_value);

                if ($user_ret && $add_ret) {
                    $this->success("积分使用成功", U("user",array('formget'=>I('formget'))));
                } else {
                    $this->error('积分使用失败');
                }
            } else
                $this->error('此用户不存在');
        }else{
            $user_db = M('app_users');
            $user_obj = $user_db->field('user_id,mobile,regist_time,user_level_id,points_value')->where('user_id=' . I('user_id'))->find();
            $this->assign("formget",I('formget'));

            $this->assign("data", $user_obj);//在 Action 类里面使用 assign 方法对模板变量赋值，无论何种变量类型都统一使用 assign 赋值
            $this->display();// 输出模版文件
        }

    }

    // 大客户管理
    public function shop_list(){

        $formget = I('formget');
        $shop_address=  $formget["shop_address"];
        $shop_name=  $formget["shop_name"];

        $formget=array('shop_address'=>$shop_address
        ,'shop_name'=>$shop_name);


        $where = " 1 " ;

        if($shop_address)
            $where = $where.' and shop_address like "%'.$shop_address.'%"';
        if($shop_name)
            $where = $where.' and shop_name like "%'.$shop_name.'%"';

        $user_shop_db=M("user_shop");
        $count=$user_shop_db->where($where)->count();

        import("Org.Util.Pagemumayi");
        $page = new \Pagemumayi($count,20);
        //分页跳转的时候保证查询条件
        foreach($formget as $key=>$val) {
            $page->parameter .= 'formget['."$key"."]=".urlencode($val)."&";
        }

        $lists = $user_shop_db->where($where)
                            ->order("shop_area,sort,time desc")
                            ->limit($page->firstRow . ',' . $page->listRows)
                            ->select();
        $this->assign('lists', $lists);
        $this->assign("formget", $formget);
        $this->assign("page", $page->show('Admin'));
        $this->assign('total_count', $count);
//        dump($lists);
//        die;
        $this->display();
    }
    /**
     *大客户信息修改
     **/
    function  shop_edit(){
        if (IS_POST) {
            $shop_id = I("shop_id");
            $user_shop_db = M('user_shop');

            $data = array(
                'shop_name' => I('shop_name'),
                'shop_address' => I('shop_address'),
                'shop_latit' =>  I('shop_latit'),
                'shop_longit' =>  I('shop_longit'),
                'shop_scope' =>  I('shop_scope'),
                'shop_area'=>I('shop_area'),
                'sort'=>I('sort')
            );

            $up_ret = $user_shop_db->where('shop_id='.$shop_id)->save($data);

            if ($up_ret) {
                $this->success("大客户修改成功", U("shop_list",array('formget'=>I('formget'))));
            } else {
                $this->error('大客户修改失败');
            }

        }else{
            $user_shop_db = M('user_shop');
            $user_shop_obj = $user_shop_db->where('shop_id=' . I('shop_id'))->find();
            $this->assign("formget",I('formget'));

            $this->assign("data", $user_shop_obj);//在 Action 类里面使用 assign 方法对模板变量赋值，无论何种变量类型都统一使用 assign 赋值
            $this->display();// 输出模版文件
        }

    }
    /**
     *大客户信息修改
     **/
    function  shop_add(){
        if (IS_POST) {

            $user_shop_db = M('user_shop');
                $data = array(
                    'shop_name' => I('shop_name'),
                    'shop_address' => I('shop_address'),
                    'shop_latit' =>  I('shop_latit'),
                    'shop_longit' =>  I('shop_longit'),
                    'shop_scope' =>  I('shop_scope'),
                    'time'=>date('Y-m-d H:i;s',time()),
                    'shop_area'=>I('shop_area'),
                    'sort'=>I('sort')
                );

                $add_ret = $user_shop_db->add($data);

                if ($add_ret) {
                    $this->success("大客户添加成功", U("shop_list",array('formget'=>I('formget'))));
                } else {
                    $this->error('大客户添加失败');
                }

        }else {

            $this->display();
        }

    }
    /**
     * 大客户删除
     */
    function shop_del()
    {
        $version_db = M("user_shop");
        $ret = $version_db->where('shop_id='.I('id'))->delete();
        if ($ret) {
            $this->success("删除成功！", U("shop_list"));
        } else {
            $this->error("删除失败");
        }
    }
    /**
     *大客户信息修改
     **/
    function  shop_see(){
            $user_shop_db = M('user_shop');
            $user_shop_obj = $user_shop_db->where('shop_id=' . I('shop_id'))->find();
            $this->assign("formget",I('formget'));

            $this->assign("data", $user_shop_obj);//在 Action 类里面使用 assign 方法对模板变量赋值，无论何种变量类型都统一使用 assign 赋值
            $this->display();// 输出模版文件
    }
    /**
     *用户绑定客户信息
     **/
    function  user_shop(){

        if (IS_POST) {
            $shop_id = I("is_shop");
            $user_id = I("user_id");
            $user_db = M('app_users');

            $up_ret = $user_db->where('user_id='.$user_id)->setField(array('is_shop'=>$shop_id));

            if ($up_ret) {
                $this->success("用户绑定客户成功", U("user",array('formget'=>I('formget'))));
            } else {
                $this->error('用户绑定客户失败');
            }
        }else{
            $user_db = M('app_users a ');
            $user_obj = $user_db->where('user_id=' . I('user_id'))->find();
            $this->assign("formget",I('formget'));
            $this->assign('shops',M('user_shop')->select());
            $this->assign("data", $user_obj);//在 Action 类里面使用 assign 方法对模板变量赋值，无论何种变量类型都统一使用 assign 赋值
            $this->display();// 输出模版文件
        }

    }

    /**
     * 大客户的下单量
     */
    function shop_ordercount_list(){

        $formget = I('formget');
        $start_time = $formget['start_time'];
        $end_time = $formget['end_time'];
        $mobile = $formget['mobile'];
        $shop_name = $formget['shop_name'];

        if(empty($start_time))
            $start_time = date('Y-m-d',time());
        if(empty($end_time))
            $end_time = date('Y-m-d',time());

        $formget=array('start_time'=>$start_time,
                        'end_time'=>$end_time
                        ,'mobile'=>$mobile,
                        'shop_name'=>$shop_name);

        $where = ' where  o.`status`=7 ';

        $where = $where." and o.order_time >= '".$start_time." 00:00:00'";
        $where = $where." and o.order_time <= '".$end_time." 23:59:59' ";

        $user_where = ' where 1 ' ;
        if(!empty($mobile))
            $user_where = $user_where." and a.mobile like '%".$mobile."%'";
        if(!empty($shop_name))
            $user_where = $user_where." and s.shop_name like '%".$shop_name."%'";

//        $count_sql ="select count(*) as count from db_user_shop s  left join db_app_users a on s.shop_id = a.is_shop " .$user_where;
//        dump($count_sql);
//        $count=M()->query($count_sql);
//
//        import("Org.Util.Pagemumayi");
//        $page = new \Pagemumayi($count,20);
//        //分页跳转的时候保证查询条件
//        foreach($formget as $key=>$val) {
//            $page->parameter .= 'formget['."$key"."]=".urlencode($val)."&";
//        }

        $shop_sql = "select s.shop_id".
                           " ,s.shop_name".
                    " ,s.shop_area".
                    "   ,a.mobile".
                    "   ,IF(order_src.order_counts IS NULL, 0, order_src.order_counts) as order_counts ".
                    "  ,IF(order_src.order_amount IS NULL, 0.00, order_src.order_amount) as order_amount".
                    "  ,IF(order_src.real_amount IS NULL, 0.00, order_src.real_amount) as real_amount".
                    "    ,order_src.order_time".
                    "  from db_user_shop s ".
                    "  left join db_app_users a on s.shop_id = a.is_shop".
                    "   left join ".
                    "   ( select user_id,count(order_id) as order_counts,sum(order_amount) as order_amount ,sum(o.real_amount) as real_amount , DATE_FORMAT(o.order_time,'%Y-%m') as order_time from db_order o ".
                            $where.
                    "       GROUP BY user_id".
                    "     )as order_src on order_src.user_id = a.user_id ".
                        $user_where.
                    "     order by s.shop_area,s.sort,s.time";

        $data = M()->query($shop_sql);

        $this->assign("formget",$formget);
        $this->assign('lists',$data);
        $this->display();// 输出模版文件
    }
}